import { Button, PasswordInput, TextInput } from '@mantine/core';
import { useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

export function RegisterPage() {
    const navigate = useNavigate();
    const form = useForm({
        initialValues: {
            username: '',
            password: '',
            email: '',
        },
        validate: {
            username: (value) => (value.length < 3 ? '用户名至少3个字符' : null),
            password: (value) => (value.length < 6 ? '密码至少6个字符' : null),
            email: (value) => (/^\S+@\S+$/.test(value) ? null : '无效的邮箱格式'),
        },
    });

    const handleSubmit = async (values: typeof form.values) => {
        try {
            await axios.post('/qa-api/register', values);
            notifications.show({
                title: '注册成功',
                message: '请登录您的账号',
                color: 'green',
            });
            navigate('/login');
        } catch (err) {
            const error = err as Error & { response?: { data?: { error?: string } } };
            notifications.show({
                title: '注册失败',
                message: error.response?.data?.error || error.message || '服务器错误',
                color: 'red',
            });
        }
    };

    return (
        <div className="min-h-screen bg-gray-100 p-4 flex items-center justify-center">
            <div className="max-w-md w-full p-6 bg-white rounded-lg shadow-md">
                <h2 className="text-2xl font-bold mb-6 text-center">用户注册</h2>
                <form onSubmit={form.onSubmit(handleSubmit)}>
                    <TextInput
                        label="用户名"
                        placeholder="输入用户名"
                        {...form.getInputProps('username')}
                        className="mb-4"
                    />
                    <TextInput
                        label="邮箱"
                        placeholder="输入邮箱"
                        {...form.getInputProps('email')}
                        className="mb-4"
                    />
                    <PasswordInput
                        label="密码"
                        placeholder="输入密码"
                        {...form.getInputProps('password')}
                        className="mb-6"
                    />
                    <Button type="submit" fullWidth>
                        立即注册
                    </Button>
                </form>
            </div>
        </div>
    );
}
